<?php
class Controller_Questions extends Controller_Base
{
	public function index()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Questions';
		$this->view->title = 'Questions Menu';
	}
	
	public function add()
	{
		$this->view->pageTitle = self::BASE_PAGE_TITLE.' --- Add Question';
		$this->view->title = $this->view->pageTitle;
		$modelTests = new Model_DbTable_Tests();
		$this->view->tests = $modelTests->fetchAll();
		$this->view->errorMessage = '';
		if($this->request->isPost()){
			$testId = (int)$this->request->getParam('testId');
			$desc = (string)$this->request->getParam('desc');
			$model = new Model_Questions();
			$isValid = $model->isValid($testId, $desc);
			if(!$isValid){
				$this->view->errorMessage = ' invalid';
				return;
			}else{
				$model->save($testId, $desc);
				$this->redirect(array('ctrl' => 'questions', 'act' => 'lists'));
			}
		}
	}
	
	public function update()
	{
		
	}
	
	public function delete()
	{
		
	}
	
	public function lists()
	{
		$this->view->testId = (int)$this->request->getParam('testId');
		$model = new Model_DbTable_Tests();
		$this->view->tests = $model->fetchAll();
		if($this->view->testId > 0){
			$model = new Model_DbTable_Questions();
			$this->view->questions = $model->select(array(), array('testId' => $this->view->testId));
		}
	}
	
	public function table()
	{
		$testId = (int)$this->request->getParam('testId');
		if($testId > 0){
			$model = new Model_DbTable_Questions();
			$this->view->questions = $model->select(array(), array('testId' => $testId));
		}
	}
	
	public function testQuestions()
	{
		$this->disabledView = true;
		$testId = (int)$this->request->getParam('testId');
		$model = new Model_DbTable_Questions();
		$questions = $model->select(array('id', '_desc'), array('testId' => $testId));
		header('Content-type: text/json');
		echo json_encode($questions);
	}
}